package com.hyfrogx.modules.app.controller;

/**
 * @ClassName: ApiAskUserController
 * @Description: 邀请改版控制类
 * @author Li
 * @date 2018-10-31 09:20:34
 *
 */

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.utils.RedisUtils;
import com.hyfrogx.modules.app.entity.HyAskCode;
import com.hyfrogx.modules.app.entity.HyInviteInfo;
import com.hyfrogx.modules.app.entity.Sms;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.HyAskCodeService;
import com.hyfrogx.modules.app.service.HyInviteInfoService;
import com.hyfrogx.modules.app.service.SmsService;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;


@RestController
@RequestMapping(value = "api/web/AskUser")
@Api(value = "WebAskController", tags = {"H5--邀请好友"})
public class ApiWebAskUserController{

    @Autowired
    HyAskCodeService askCodeService;

    @Autowired
    UserService userService;

    @Autowired
    SmsService smsService;

    @Autowired
    HyInviteInfoService inviteInfoService;

    @Autowired
    RedisUtils redisUtils;

    /**
     * @param inviteInfo
     * @return {@link Boolean} 1.判断用户是否可以参加活动
     * @throws Exception
     */
    @PostMapping(value = "/validate")
    @ApiOperation("判断用户是否可以参加活动")
    public R validate(@RequestBody  HyInviteInfo inviteInfo){
        if (inviteInfo.getTphone() == null) {
            return R.error("被邀请用户手机号不能为空.");
        }
        // 判断是否接受过邀请
        HyInviteInfo oldInfo = inviteInfoService.getHyInviteInfoByPhone(inviteInfo.getTphone());
        if (oldInfo != null) {
            return R.error("对不起,您已接受过邀请");
        }
        return R.ok();
    }

    /**
     * 2.发送短信验证码
     *
     * @param tphone
     * @return
     */
    @PostMapping("sendYzm")
    @ApiOperation("发送短信验证码")
    public  R sendYzm(@RequestParam("tphone") String tphone,
                      @RequestParam(value = "nationcode", defaultValue = "86") String nationcode) {
        // 先去redis 查询是否 60S内已经发送
        Object tempCode = redisUtils.get(FrogConstant.INVITE_YZM + tphone);
        if (tempCode != null) {
            return R.ok("验证码未失效，请失效后再次申请");
        }

        // 获取6位验证码
        String code = RandomUtil.randomNumbers(6);

        // 保存进redis 过期时间120秒
        redisUtils.set(FrogConstant.INVITE_YZM + tphone, code, FrogConstant.SMS_CODE_EXPIRE);

        // 发送短信 测试可用先注释,通过redis查看
        ArrayList<String> params = new ArrayList<>();
        params.add(code);
        params.add("2");
        boolean issuccess = smsService.sendSms(tphone, FrogConstant.SMS_TMP_YZM, params);
        if (issuccess) {
            // 持久化
            Sms o = new Sms();
            o.setPhone(tphone);
            o.setStatus(1);
            o.setDate(new Date());
            o.setContent("手机号：" + tphone + ";短信模板：" + FrogConstant.SMS_TMP_YZM + ";验证码：" + code);
            smsService.createSms(o);
            return R.ok();
        }
        // 发送失败删除redis
        redisUtils.delete(FrogConstant.INVITE_YZM + tphone);

        return R.error("验证码发送失败!");
    }

    /**
     * @param inviteInfo
     * @return  3.确认接收邀请
     * @throws Exception
     */
    @PostMapping(value = "/create")
    @ApiOperation("确认接收邀请")
    public  R create(@RequestBody  HyInviteInfo inviteInfo) {
            // 验证码,tphone,邀请码web端回传
            if (inviteInfo.getTphone() == null) {
                return R.error("受邀请用户手机号必传");
            }
            if (inviteInfo.getTaskcode() == null) {
                return R.error("用户邀请码必传");
            }
            if (inviteInfo.getYzm() == null) {
                return R.error("验证码必传");
            }
            if (StringUtils.isEmpty(inviteInfo.getYzm()) || inviteInfo.getYzm().length() != 6) {
                return R.error("验证码格式错误");
            }
            /**
             * 登录的验证码确认。redis存储前缀和获取前缀不统一
             */
            if (ObjectUtil.isNull(redisUtils.get(FrogConstant.INVITE_YZM+inviteInfo.getTphone()))) {
                return R.error("验证码未发送或验证码已过期");
            }
            // 查看填写的手机号是不是邀请码所有者本人
            HyAskCode askCode = askCodeService.getAskCodeByCode(inviteInfo.getTaskcode());
            if (askCode == null) {
                return R.error("对不起,该邀请码无效,请确认一遍您的邀请码");
            }
            // 查询这个邀请码直接邀请人的所有信息
            User suser = userService.getById(askCode.getUid());

            if (suser.getPhone().equals(inviteInfo.getTphone())) {
                return R.error("这个邀请码归属您所填写的手机号,您不能邀请自己");
            }
            String value = redisUtils.get(FrogConstant.INVITE_YZM+inviteInfo.getTphone());
            if (!value.equals(inviteInfo.getYzm())) {
                return R.error("验证码错误或超时");
            }
            User tuser = userService.getUserByPhone(inviteInfo.getTphone());
            if (ObjectUtil.isNotNull(tuser))
            {
                inviteInfo.setTuid(tuser.getUid());
            }
            Boolean b = inviteInfoService.createInviteInfo(inviteInfo);
            if (b)
            {
                return R.ok();
            }
            else {
                return R.error();
            }
    }

    /**
     * @param hyAskCode
     * @return {@link Boolean} 4.根据邀请码获取邀请者信息
     * @throws Exception
     */
    @PostMapping(value = "/getInfoByCode")
    @ApiOperation("根据邀请码获取邀请者信息")
    public  R getInfoByCode(@RequestBody HyAskCode hyAskCode){
        if (hyAskCode.getAskcode() == null) {
            return R.error("邀请码不能为空");
        }
        // 通过H5传过来的邀请码获取师傅uid
        HyAskCode askCode = askCodeService.getAskCodeByCode(hyAskCode.getAskcode());
        if (askCode == null) {
            return R.error("对不起,该邀请码错误,请确认一遍邀请码");
        }
        // 查询这个邀请码直接邀请人的所有信息
        User suser = userService.getById(askCode.getUid());
        if (suser == null) {
            return R.error("邀请码所有者信息异常");
        } else {
            return R.ok().put("suser",suser);
        }
    }


}

